/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 
package buco.core.api;

import java.util.Comparator;

/*
 * Represents versions of packages and bundles according to OSGi R4 Core Spec, p. 29
 */
public class Version implements Comparator<Version> {

	private int major; 
	private int minor; 
	private int micro;
	private String qualifier;
	
	public int getMajor() {
		return major;
	}
	
	public int getMinor() {
		return minor;
	}
	
	public int getMicro() {
		return micro;
	}
	
	public String getQualifier() { 
		return this.qualifier; 
	}

	public Version(int major, int minor, int micro) {
		this.major = major;  
		this.minor = minor; 
		this.micro = micro; 
	}
	
	public Version(int major, int minor, int micro, String qualifier) {
		this.major = major;  
		this.minor = minor; 
		this.micro = micro; 
		this.qualifier = qualifier; 
	}

	/*
	 * Examples: 1.1; 1; 1.2.3; 1.2.3.v243343
	 */
	public static Version fromString(String input) {
		input = input.trim();
		int[] arr = new int[3]; 
		String qualifier = null; 
		
		String[] elements = input.split("\\."); 
		for(int i=0; i < Math.min(3, elements.length); i++) {
			arr[i] = Integer.valueOf(elements[i]); 
		}
		
		if(elements.length == 4) { 
			qualifier = elements[3]; 
		}
		
		return new Version(arr[0], arr[1], arr[2], qualifier); 
	}
	
	public boolean isLessThan(Version version) {
		return this.compareTo(version) < 0; 
	}
	
	public boolean isLessThanOrEqual(Version version) {
		return isLessThan(version) || this.compareTo(version) == 0; 				
	}
	
	public int compareTo(Version version) { 
		return compare(this, version); 
	}

	@Override
	public int compare(Version a, Version b) {
		if(a.getMajor() != b.getMajor()) {
			if(a.getMajor() > b.getMajor()) {
				// a > b
				return 1; 
			}
			// a < b
			return -1;
		}		
		if(a.getMinor() != b.getMinor()) {
			if(a.getMinor() > b.getMinor()) {
				// a > b
				return 1; 
			}
			// a < b
			return -1;
		}		
		if(a.getMicro() != b.getMicro()) {
			if(a.getMicro() > b.getMicro()) {
				// a > b
				return 1; 
			}
			// a < b
			return -1;
		}
		// then it must be equal 
		return 0;			
	}
	
	@Override
	public String toString() {
		String version = String.valueOf(major) + "." + 
				String.valueOf(minor)  + "." +
				String.valueOf(micro);
		
		if(qualifier != null) {
			version += "." + qualifier; 
		}
		
		return version; 
	}
}
